package softtech.apps.dangtinraovat;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import softtech.apps.adapter.ConversationAdapter;
import softtech.apps.adapter.MessageEndlessAdapter;
import softtech.apps.model.Conversation;
import softtech.apps.model.DatabaseHandler;
import softtech.apps.utilities.HttpRequest;
import softtech.apps.utilities.Utilities;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class ActivityConversation extends Activity{
    private static final String TAG = "ChatActivity";
    public static final String REG_ID = "regId";
//    private static MessageEndlessAdapter chatArrayAdapter;
//    private IntefaceConversationListView listView;
    
    private static ConversationAdapter chatArrayAdapter;
    private ListView listView;
    
    private static EditText chatText;
    private Button buttonSend;

    Intent intent;
	String regId;
	String touserid;
	
	final List<String> regIdList = new ArrayList<String>();
	private final static int ITEM_PER_REQUEST = 30;
	int mult = 5;
	
	private DatabaseHandler dbHandler;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.conversation);
        // Get REG ID here and store in current device
        Intent i = getIntent();
        touserid = i.getStringExtra("user_id");
        Log.d(TAG, "To user id = "+touserid);
		final Context context = this;
        // Message hien thi tren 1 listview
		dbHandler = new DatabaseHandler(context);
		
		this.registerReceiver(receiver, filter);
		
		chatArrayAdapter = new ConversationAdapter(getApplicationContext(), R.layout.conversation_item);
		listView = (ListView) findViewById(R.id.lvConversation);
		listView.setAdapter(chatArrayAdapter);
        Getconversation(touserid);
    }
    public void Getconversation(final String touserid){	
		new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                String msg = "";
                try {
                	HttpRequest req = new HttpRequest();
                	List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
                	nameValuePair.add(new BasicNameValuePair("userid",touserid));
                	String a = req.makeServiceCall(Utilities.APP_SERVER_URL_GET_REG,HttpRequest.POST,nameValuePair);
                	Log.d(TAG, "Json ="+a);
                	try {
						JSONObject jsonObj = new JSONObject(a);
						JSONArray contacts = jsonObj.getJSONArray("regIdlist");
						for (int ii = 0; ii < contacts.length(); ii++) {
							JSONObject c = contacts.getJSONObject(ii);
							String regId = c.getString("gcm_regid");
							Log.d(TAG, "RegID = "+regId);
							regIdList.add(regId);
						}
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					};
					
                } catch (Exception ex) {
                	ex.printStackTrace();
                    msg = "Error :" + ex.getMessage();
                }
                return msg;
            }

            @Override
            protected void onPostExecute(String msg) {
            	loadData();
            }
        }.execute(null, null, null);
	}
    private boolean sendChatMessage(View view,final String mes){
           if (view == findViewById(R.id.buttonSend)) {
            Log.d(TAG,"Reg ID luc dang ky xong = "+regId);
            new AsyncTask<Void, Void, String>() {
            	
				@Override
				protected void onPreExecute() {
					// TODO Auto-generated method stub
					super.onPreExecute();
					// Tin nhan gui di nam o ben phai       
                	Conversation aConversation = new Conversation(
            				0,
            				mes,
            				Integer.parseInt(touserid),
            				1);
	            	dbHandler.insertMessage(aConversation);
	            	chatArrayAdapter.add(aConversation);// Gia tri mac dinh
                	chatText.setText("");
				}

				@Override
                protected String doInBackground(Void... params) {
                    String msg = "";
                    try {
                    	Log.d(TAG,"Send message to server here"); 
                    	HttpRequest req = new HttpRequest();
                    	List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
                    	Log.d(TAG,"Kich thuoc regidList = "+regIdList.size());
                    	for(String reg:regIdList){
                    		nameValuePair.add(new BasicNameValuePair("regId[]", reg));
                    	}
                    	Log.d(TAG, "Thong diep se gui di = "+mes);
                    	nameValuePair.add(new BasicNameValuePair("message",mes));
                    	nameValuePair.add(new BasicNameValuePair("FromUserId","88"));
                    	String a = req.makeServiceCall(Utilities.APP_SERVER_URL_SEND_MESSAGE,HttpRequest.POST,nameValuePair);
                    } catch (Exception ex) {
                    	ex.printStackTrace();
                        msg = "Error :" + ex.getMessage();
                    }
                    return msg;
                }

                @Override
                protected void onPostExecute(String msg) {
                	// Hien thi trang thai dang gui tin nhan
                }
            }.execute(null, null, null);
        }
        return true;
    }
    public final static Handler handle1 =new Handler(){

		@Override
		public void handleMessage(android.os.Message msg) {
			// TODO Auto-generated method stub
			Bundle b=msg.getData();
			String message= b.getString("message");
			Log.d(TAG, "Message nhan duoc = "+message);
			chatArrayAdapter.add(new Conversation(1, message,1,1)); // Tin nhan nhan duoc nam ben trai
			//chatArrayAdapter.add(new Conversation(side, message,1,1));
			//side = !side; // Chuyen ben nhan duoc, khong nhan duoc
		}
		
	};
	  // Set When broadcast event will fire.
    private IntentFilter filter = new IntentFilter(Utilities.MESSAGE_BROADCAST);
	private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
           Log.d("MESSAGE", "Da nhan duoc tin nhan tu phia server");
           String message = intent.getStringExtra("message");
           int fromUserId = intent.getIntExtra("fromUserId",0);
           int mesServerId = intent.getIntExtra("mesServerId",0);
           chatArrayAdapter.add(new Conversation(1,message, fromUserId,mesServerId));
        }
    };
    
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		this.unregisterReceiver(receiver);
	}
	private List<Conversation> createItems(int mult) {
		List<Conversation> result = new ArrayList<Conversation>();
		// Query from database to add this
		result = dbHandler.getTopMessage(mult,0,Integer.parseInt(touserid));
		return result;
	}

	public void loadData() {
		System.out.println("Load data");
		mult = 5;
		// We load more data here
		GetConversation fl = new GetConversation();
		fl.execute();
		
	}
	private class GetConversation extends AsyncTask<String, Void, List<Conversation>> {

		@Override
		protected List<Conversation> doInBackground(String... params) {	
			return createItems(mult);
		}

		@Override
		protected void onPostExecute(List<Conversation> result) {			
			super.onPostExecute(result);
			Log.d(TAG, "Tong so record get duoc = "+result.size());
			int side = 1;
			for(Conversation a :result){
				if(a.isLeft() == 0){
					side = 0;
				}
				chatArrayAdapter.add(new Conversation(side, a.getMessage(), a.getUserIdFrom(), a.getId_server()));
			}
			chatText = (EditText) findViewById(R.id.chatText);
			
            chatText.setOnKeyListener(new OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    	String mes = chatText.getText().toString();
                    	if(!TextUtils.isEmpty(mes)){
                    		return sendChatMessage(v,mes);
                    	}
                    }
                    return false;
                }
            });    
            buttonSend = (Button) findViewById(R.id.buttonSend);
            buttonSend.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                	Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                	Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                	r.play();
                	String mes = chatText.getText().toString();
                	if(!TextUtils.isEmpty(mes)){
                		sendChatMessage(view,mes);
                	}
                }
            });
		}
	}
}